/*
 * @lc app=leetcode.cn id=103 lang=javascript
 *
 * [103] 二叉树的锯齿形层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
  const res = [];
  if (!root) return res;
  let queue = [root];
  let order = true;
  while (queue.length > 0) {
    const temp = queue;
    queue = [];
    const curLevel = [];
    for (const node of temp) {
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
    if (!order) temp.reverse();
    for (const node of temp) {
      curLevel.push(node.val);
    }
    res.push(curLevel);
    order = !order;
  }
  return res;
};
// @lc code=end
